package com.rainner.admin.action;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.mail.EmailException;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.rainner.admin.action.base.EasyuiAction;
import com.rainner.admin.defined.PermissionDefined;
import com.rainner.admin.defined.SystemDefine;
import com.rainner.admin.javabean.ReaderBean;
import com.rainner.admin.server.ReaderServer;
import com.rainner.admin.server.RolePermissionServer;
import com.rainner.admin.util.email.SendEmailUtil;

@Results({ @Result(name = "EMAIL", type = "freemarker", location = "/WEB-INF/content/email/index.ftl") })
public class SendEmailAction extends EasyuiAction {
	private static final long serialVersionUID = 1L;

	private final String base = "/email";
	private String type;
	private ReaderServer readerServer = new ReaderServer();
	private RolePermissionServer permissionServer = new RolePermissionServer();
	
	@Actions({ @Action(base), @Action(base + "/{type}") })
	public String readerManage() throws SQLException, EmailException {
		Object username = ServletActionContext.getRequest().getSession().getAttribute("username");
		if (type == null && username != null) {
			return "EMAIL";
		}else if(username ==null){
			return null;
		}
		if (SystemDefine.EMAIL_INIT.equals(type)) {
			map.put("rows", readerServer.oweReaderData(page, rows));
			map.put("total", readerServer.countOweReaderData());
		}else if(SystemDefine.EMAIL_SEND.equals(type) && permissionServer.checkPermission(PermissionDefined.SEND_EMAIL, username.toString())){
			List<ReaderBean> beanList = readerServer.oweReaderData(0, 0);
			for (ReaderBean readerBean : beanList) {
				SendEmailUtil.sendEmail(readerBean.getReaderName(), readerBean.getReaderEmail(), "");
			}
		}
		return MAP;
	}

	public void setType(String type) {
		this.type = type;
	}
}
